<template>
  <div
    ref="scrollContainer"
    class="scroll_container flex_grow_1 flex_shrink_1 scrollbar_default"
    @scroll="doScroll"
    :style="{
      'padding-bottom': paddingBottom
    }"
  >
    <div id="scrollWrap">
      <slot />
    </div>
    <div class="btns" :class="{ fixed: isScroll }" :style="{ bottom: isScroll ? fixedBottom + 'px' : 'auto' }" ref="btns">
      <slot name="btns" />
    </div>
  </div>
</template>

<script>
import elementResizeDetectorMaker from 'element-resize-detector';

export default {
  name: 'ScrollContainer',
  props: {
    index: {
      type: String,
      default: ''
    },
    fixedBottom: {
      type: Number,
      default: 15
    },
  },
  watch: {
    $route: {
      handler(newVal) {
        const cache = this.$store.getters.scrollCache[newVal.name + this.index];
        if (cache) {
          this.$refs.scrollContainer.scrollTop = cache; // 是否有缓存滚动条
        }
      }
    }
  },
  created() {
    const routeName = this.$route.name;
    if (this.scrollCacheList.includes(routeName)) {
      this.$store.commit('layout/setScrollCache', { [routeName + this.index]: 0 });
    }
  },
  mounted() {
    this.$nextTick(() => {
      const erd = elementResizeDetectorMaker();
      erd.listenTo(document.getElementById('scrollWrap'), () => {
        this.clientResize();
      });
    });
  },
  data() {
    return {
      isScroll: false,
      paddingBottom: 0,
      isResize: false,
      timeout: null,
      scrollCacheList: ['Index', 'Permission'] // 需要缓存滚动条的路由，填入路由的 name
    };
  },
  methods: {
    clientResize() {
      const container = this.$el,
        btns = this.$refs.btns;
      // console.log(container, btns);
      if (btns && btns.children && btns.children.length) {
        this.isScroll = container.scrollHeight > container.clientHeight;
        this.paddingBottom = this.isScroll ? btns.clientHeight + 5 + 'px' : 0;
      }
    },
    doScroll(e) {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => { // 防抖
        const routeName = this.$route.name;
        if (this.scrollCacheList.includes(routeName)) {
          this.$store.commit('layout/setScrollCache', { [routeName + this.index]: e.target.scrollTop });
        }
      }, 500);
    }
  }
};
</script>

<style lang="scss" scoped>
.scroll_container {
  min-height: 100px;
  margin: 0 -30px;
  padding: 0 30px;
}
.btns {
  width: 100%;
  text-align: center;
  > * {
    min-width: 80px;
    display: inline-block;
    vertical-align: middle;
    margin: 20px 0;
    & + .el-button {
      margin-left: 25px;
    }
  }
  &.fixed {
    width: calc(100% - 40px);
    background: #ffffff;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    position: absolute;
    left: 20px;
    z-index: 99;
  }
}
</style>
